#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>

void ChildRun()
{
    int cnt = 5;
    while (cnt--)
    {
        std::cout << "I am child process, my pid: " << getpid() << std::endl;
        sleep(1);
    }
}
void test1()
{
    pid_t id = fork();
    if (id == 0)
    {
        // 子进程
        ChildRun();
        exit(0);
    }
    // 父进程

    int status = 0;
    waitpid(id, &status, 0);

    std::cout << "Child quit sucess, quit code: " << ((status >> 8) & 0xFF) << ", quit signal: " << (status & 0x7F) << std::endl;
}
void test2()
{
    pid_t id = fork();
    if (id == 0)
    {
        execl("/usr/bin/ls", "-l", "-a", nullptr);
    }
    // 父进程

    int status = 0;
    waitpid(id, &status, 0);
    std::cout << "new process quit sucess, quit code: " << ((status >> 8) & 0xFF) << ", quit signal: " << (status & 0x7F) << std::endl;
}
void test3()
{
    int fd = open("bite", O_CREAT | O_WRONLY, 0666);
    if (fd < 0)
    {
        perror("open");
        exit(-1);
    }
    char message[] = "i like linux!";
    int n = write(fd, message, sizeof(message));
    if (n == -1)
    {
        perror("write");
        exit(-1);
    }
    close(fd);

    fd = open("bite", O_RDONLY, 0666);
    char buffer[128];
    n = read(fd, buffer, sizeof(buffer));
    if (n == -1)
    {
        perror("write");
        exit(-1);
    }

    std::cout << buffer << std::endl;
    close(fd);
}
void test4()
{

    FILE *pf = fopen("bite", "w+");
    fprintf(pf, "linux so easy!");

    
    fseek(pf, 0 , SEEK_SET);
    char buffer[128];
    fgets(buffer, sizeof(buffer), pf);

    std::cout << buffer << std::endl;
    fclose(pf);
}
int main()
{
    test1();
    return 0;
}